package com.web.utils;

import java.nio.ByteBuffer;
import java.util.Random;

/**
 * @Author: wws
 * @Date: 2021/1/30 15:04
 * describe:
 */
public class ToolUtil {

    private final static String regex = "^[A-Fa-f0-9]+$";
    private static final char[] hexCode = "0123456789ABCDEF".toCharArray();

    private static int MAX = 0xFFFFFFFF;
    private static int MIN = 0xFFFFF000;
    private static Random random = new Random();

    public static boolean checkIsHexadecimal(String str) {
        return str.matches(regex);
    }

    /**
     * 生成随机生成不在指定范围内的Int型整数
     * @return
     */
    public static Integer generateAddr() {
        int addr;
        do {
            addr = random.nextInt();
        } while (MIN < addr && addr < MAX);
        return addr;
    }



    /**
     * 将字节数组转成字符串
     * @param data 字节数组
     * @return 结果
     */
    public static String printHexBinary(byte[] data) {
        StringBuilder r = new StringBuilder(data.length * 2);
        for (byte b : data) {
            r.append(hexCode[(b >> 4) & 0xF]);
            r.append(hexCode[(b & 0xF)]);
        }
        return r.toString();
    }
    //将字符串转化为16位进制byte[]数组
    public static byte[] toByteArray(String hexString) {
        hexString = hexString.replaceAll(" ", "");
        final byte[] byteArray = new byte[hexString.length() / 2];
        int k = 0;
        for (int i = 0; i < byteArray.length; i++) {//因为是16进制，最多只会占用4位，转换成字节需要两个16进制的字符，高位在先
            byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);
            byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);
            byteArray[i] = (byte) (high << 4 | low);
            k += 2;
        }
        return byteArray;
    }

    //生成长度为n的随机字节数组
    public static byte[] CalAppNonce(int n) {
        byte[] b = new byte[n];
        Random random = new Random();
        for (int i = 0; i < b.length; i++) {
            b[i] = (byte) random.nextInt(256);
        }
        return b;
    }


    /**
     * 字节数组转单精度
     * @param b
     * @return
     */
    public static Float bytesToFloat(byte[] b) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(4);
        byteBuffer.put(b[3]);
        byteBuffer.put(b[2]);
        byteBuffer.put(b[1]);
        byteBuffer.put(b[0]);
        return byteBuffer.getFloat(0);
    }


    /**
     * byte[]转int
     * @param bytes 需要转换成int的数组
     * @return int值
     */
    public static int byteArrayToInt(byte[] bytes) {
        int value=0;
        for(int i = 0; i < 4; i++) {
            int shift= (3-i) * 8;
            value +=(bytes[i] & 0xFF) << shift;
        }
        return value;
    }

    /**
     * 转化帧计数器
     */
    public static byte[] FCNTToBytes(long n) {
        byte[] b = new byte[2];
        b[0] = (byte) (n & 0xff);
        b[1] = (byte) (n >> 8 & 0xff);
        return b;
    }
}
